<template>
  <div class="table-page">
    <div class="button-group">
      <a-button type="primary" style="width: 100px" @click="exportTableChange()">
        <template #icon>
          <icon-share-external />
        </template>
        <!-- Use the default slot to avoid extra spaces -->
        <template #default>导出</template>
      </a-button>
      <a-button type="outline" style="width: 100px; margin-left: 16px" @click="goBack()">
        <template #icon>
          <icon-left />
        </template>
        <template #default>返回</template>
      </a-button>
    </div>
    <GiTable
      row-key="name"
      :title="title"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: true, y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      :disabled-tools="['size']"
      :disabled-column-keys="['name']"
      @refresh="tableSearch"
    >
    </GiTable>
  </div>
</template>

<script setup lang="ts">
import { debounce } from 'lodash-es'
import * as XLSX from 'xlsx'
import { onMounted, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRoute, useRouter } from 'vue-router'
import { getSignlist } from '@/apis/meet'
import type { TableInstanceColumns } from '@/components/GiTable/type'
import { useTable } from '@/hooks'

defineOptions({ name: 'Meet' })
const route = useRoute()
const router = useRouter()
const { conferenceId } = route.query

const userList = ref<any>([]) // 签到人员列表
const title = ref('')

const queryForm = reactive({
  meetType: undefined,
  conference_id: conferenceId,
  sort: ['createTime,desc']
})

const {
  tableData: dataList,
  loading,
  pagination,
  search
} = useTable((page) => getSignlist({ ...queryForm, ...page }), {
  immediate: true,
  formatResult(_data1, data2: { [key: string]: any }) {
    // 确保 data2 和 data2.user 存在
    if (data2 && Array.isArray(data2.user)) {
      // 为每个用户添加唯一标识，增加空值检查
      userList.value = data2.user.map((user: any) => {
        if (!user) return null
        return {
          ...user,
          key: user.name || Math.random().toString(36).substr(2, 9)
        }
      }).filter(Boolean) // 过滤掉 null 值
      title.value = data2.RoomName || ''
    } else {
      userList.value = []
      title.value = ''
    }
    return userList.value
  }
})

const columns: TableInstanceColumns[] = [
  {
    title: '签到人员',
    dataIndex: 'name',
    slotName: 'name',
    width: 130,
    render: ({ record }) => {
      if (!record || !record.name) return '--'
      return record.name
    }
  },
  {
    title: '签到状态',
    dataIndex: 'checkinStatus',
    slotName: 'checkinStatus',
    width: 120,
    render: ({ record }) => {
      if (!record || !record.checkinStatus) return '--'
      return record.checkinStatus
    }
  },
  {
    title: '签到时间',
    dataIndex: 'checkinTime',
    slotName: 'checkinTime',
    width: 120,
    render: ({ record }) => {
      if (!record || !record.checkinTime) return '--'
      return record.checkinTime
    }
  }
]

const tableSearch = debounce(search, 500)
/**
 * 导出按钮事件
 */
const exportTableChange = () => {
  if (!userList.value?.length) {
    Message.warning('暂无数据可导出')
    return
  }
  // 1. 定义中文字段映射关系
  const headerMap = {
    name: '签到人员',
    checkinStatus: '签到状态',
    checkinTime: '签到时间'
  }

  // 2. 构建带中文表头的数据
  const ChineseData = [
    Object.values(headerMap), // 中文表头
    ...userList.value.map((item) => {
      if (!item) return ['--', '--', '--']
      return [
        item.name || '--',
        item.checkinStatus || '--',
        item.checkinTime || '--'
      ]
    })
  ]

  // 3. 创建带中文表头的工作表
  const worksheet = XLSX.utils.aoa_to_sheet(ChineseData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, worksheet, '签到记录')
  XLSX.writeFile(wb, '签到表.xlsx')
}

const goBack = () => {
  router.push('/meet/meet')
}

onMounted(() => {})
</script>

<style lang="scss" scoped>
.button-group {
  display: flex;
  margin-bottom: 16px;
}
</style>
